package com.fzf.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fzf.org.dao.entities.BlogDO;
import com.fzf.org.dao.mapper.BlogMapper;
import com.fzf.org.dto.req.blog.BlogReqDTO;
import com.fzf.org.dto.req.draft.DraftReqDTO;
import com.fzf.org.dto.resp.blog.BlogDTO;
import com.fzf.org.exception.BizException;
import com.fzf.org.exception.BizExceptionTypeEnum;
import com.fzf.org.page.PageRequest;
import com.fzf.org.page.PageResponse;
import com.fzf.org.service.BlogsService;
import com.fzf.org.toolkit.BasicContext;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class BlogsServiceImpl implements BlogsService {

    private final BlogMapper blogMapper;
    private final RestTemplate restTemplate;


    @Override
    public PageResponse<BlogDTO> listUsersBlogs(PageRequest pageRequest) {
        if (pageRequest == null) {
            throw new BizException(BizExceptionTypeEnum.PARAM_ERROR);
        }

        IPage<BlogDO> page = new Page<>(pageRequest.getCurrent(), pageRequest.getSize());
        LambdaQueryWrapper<BlogDO> wrapper = new LambdaQueryWrapper<BlogDO>()
                .eq(BlogDO::getUserId, BasicContext.getBasicId());
//                .eq(BlogDO::getUserId, BasicContext.getBasicId()).ne(BlogDO::getStatus, 3);

        IPage<BlogDO> resultPage = blogMapper.selectPage(page, wrapper);
        List<BlogDTO> convertRecords = resultPage.getRecords().stream().map(
                blogDO -> BeanUtil.copyProperties(blogDO, BlogDTO.class)
        ).toList();

        return new PageResponse<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal(), convertRecords);
    }

    @Override
    public BlogDTO showBlogDetail(Long blogID) {
        BlogDO blog = blogMapper.selectOne(new LambdaQueryWrapper<BlogDO>()
                .eq(BlogDO::getUserId, BasicContext.getBasicId())
                .eq(BlogDO::getId, blogID));
//                .ne(BlogDO::getStatus, 3)); // todo

        if (null == blog) {
            throw new BizException(BizExceptionTypeEnum.BLOG_NOT_EXIST_ERROR);
        }
        return BeanUtil.copyProperties(blog, BlogDTO.class);
    }

    @Override
    public void delBlog(Long blogID) {
        int delete = blogMapper.delete(new LambdaQueryWrapper<BlogDO>()
                .eq(BlogDO::getUserId, BasicContext.getBasicId())
                .eq(BlogDO::getId, blogID));

        if (delete != 0) {
            throw new BizException(BizExceptionTypeEnum.BLOG_NOT_EXIST_ERROR);
        }
    }

    private final String REMOTE_ALGO_URL = "http://159.75.72.79:9236/text_predict";
    private static final ObjectMapper objectMapper = new ObjectMapper();


//    private boolean checkContent(BlogReqDTO blogReqDTO) {
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//
//        // 构建请求体
//        Map<String, String> requestBody = new HashMap<>();
//        requestBody.put("text", blogReqDTO.getContent());
//
//        // 创建请求实体
//        HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
//
//        // 发送请求
//        ResponseEntity<String> response = restTemplate.postForEntity(REMOTE_ALGO_URL, request, String.class);
//        try {
//            return "中性".equals(
//                    objectMapper.readValue(response.getBody(), Map.class).get("predicted_class"));
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
//    }

    public boolean checkContent(BlogReqDTO blogReqDTO) {
        final int maxAttempts = 3;
        final long delayMillis = 1000;

        int attempts = 0;

        while (attempts < maxAttempts) {
            try {
                System.out.println("--------------- Attempt: " + (attempts + 1));

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);

                Map<String, String> requestBody = new HashMap<>();
                requestBody.put("text", blogReqDTO.getContent());

                HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);

                ResponseEntity<String> response = restTemplate.postForEntity(REMOTE_ALGO_URL, request, String.class);

                Map<String, Object> responseMap = objectMapper.readValue(response.getBody(), Map.class);

                System.out.println(responseMap.get("predicted_class"));
                return !"消极".equals(responseMap.get("predicted_class")); // 积极  中性 消极
            } catch (RestClientException | JsonProcessingException e) {
                attempts++;
                System.err.println("远程请求失败，第 " + attempts + " 次尝试: " + e.getMessage());

                if (attempts >= maxAttempts) {
                    throw new RuntimeException("远程调用失败，超过最大重试次数", e);
                }
                try {
                    Thread.sleep(delayMillis); // 延迟后重试
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("重试等待被中断", ie);
                }
            }
        }
        return false;
    }


    @Override
    public void updateBlog(BlogReqDTO blogReqDTO) {
        if(!checkContent(blogReqDTO)){
            throw new BizException(BizExceptionTypeEnum.BLOG_CONTENT_ERROR);
        }
        BlogDO blog = blogMapper.selectOne(new LambdaQueryWrapper<BlogDO>()
                .eq(BlogDO::getUserId, BasicContext.getBasicId())
                .eq(BlogDO::getId, blogReqDTO.getId()));
        if (null == blog){ // 如果查不到
            throw new BizException(BizExceptionTypeEnum.BLOG_NOT_EXIST_ERROR);
        }

        blog.setContent(blogReqDTO.getContent());
        blog.setTitle(blogReqDTO.getTitle());
        blog.setStatus(2);
        int update = blogMapper.updateById(blog);
        if (update != 1) {
            throw new BizException(BizExceptionTypeEnum.BLOG_UPDATE_ERROR);
        }
    }
}
